<template>
    <view class="allPage all" id="allPage">
        <view class="head-part">
            <CustomHead mainColor="transparent" mode="back" hasEmptBar :styleClass="isFixed ? 'fixedNavClass' : ''" :headHeight.sync="headHeight">
                <view class="fixedNav" v-if="isFixed">
                    <view class="head-i" :class="{ active: fixedIdx == 0 }" @click="switchNav(0)">
                        <text class="">详情</text>
                    </view>

                    <view class="head-i" :class="{ active: fixedIdx == 1 }" @click="switchNav(1)">
                        <text class="">评价</text>
                        <text class="min">{{ commentTotal }}</text>
                    </view>
                </view>
            </CustomHead>

            <view class="product-swiper">
                <swiper class="mySwiper" :indicator-dots="false" :autoplay="true" @change="swiperChange" indicator-color="#fff" indicator-active-color="#ff7c8d">
                    <swiper-item v-for="(item, idx) in json.imgUrls" :key="idx">
                        <view class="shuffing-item" @click="previewImage(idx, json.imgUrls)">
                            <image :src="item" mode=""></image>
                        </view>
                    </swiper-item>
                </swiper>
                <view class="nums">
                    <text class="">{{ currentImg }}</text>
                    /{{ json.imgUrls.length }}
                </view>

                <!-- <view
                    class="sellOut"
                    v-if="sellClear"
                >
                    <text>抢光啦，可预约</text>
                </view> -->
            </view>
        </view>

        <view class="content mb10">
            <div class="parts">
                <view class="price">
                    <view class="price-box">
                        <!-- <text
                            class="col-r"
                            v-if="json.openPt == 1"
                        >
                            <text class="">拼团￥</text>
                            <text class="big">{{ json.salePricePt }}</text>
                        </text> -->

                        <text class="price-col">
                            <text class="">￥</text>
                            <text class="big b">{{ json.salePrice }}</text>
                        </text>
                    </view>

                    <!-- <view class="buy-btn">
                        <Count
                            :numVal.sync="json.count"
                            @change="productChange"
                            :parameter="json.id"
                            size="big"
                        />
                    </view> -->
                </view>

                <view class="name-box">
                    <!-- <text
                        v-if="json.isJingpin"
                        class="tag green lijian"
                    >
                        力荐
                    </text>
                    <image
                        v-if="json.isJingpin"
                        src="/static/images/tuijian2.png"
                        class="tuijianTag"
                        mode="heightFix"
                    /> -->
                    <text class="name">{{ json.goodsName }}</text>

                    <!-- <view class="sellNum">
                        <text class="">{{ json.saleNum }}人已买</text>
                    </view> -->
                </view>

                <view class="words-tag" v-if="json.productLabelTypeName">
                    <text class="j-tag hui f24" v-for="(labeli, idx3) in json.labelArr" :key="idx3">
                        {{ labeli }}
                    </text>
                </view>

                <!-- <view
                    class="maskBox"
                    v-if="sellClear"
                >
                    <div class="sellBox">
                        <image :src='clearImg' mode='aspectFit'></image>
                    </div>
                </view> -->
                <!-- <view class="desc" v-if="json.goodsDesc">
                    <view class="col-hui ">
                        <text class="">{{ json.goodsDesc }}</text>
                    </view>
                </view> -->

                <!-- 底部三个 -->
                <div class="handle-foot">
                    <Handle :json="json" />
                </div>
            </div>
        </view>
        <!-- 服务和规则************************************************ -->

        <div class="parts line-box">
            <div class="line-item" @click="serverClick('server')">
                <span class="label">服务</span>
                <div class="middle words">
                    <div class="words-i">
                        <img src="/static/images/g_gou1.png" />
                        <span>保密发货</span>
                    </div>

                    <div class="words-i">
                        <img src="/static/images/g_gou1.png" />
                        <span>正品保证</span>
                    </div>

                    <div class="words-i">
                        <img src="/static/images/g_gou1.png" />
                        <span>7天退换货</span>
                    </div>
                </div>
                <span class="r-icon">
                    <i class="iconfont icon-xiangyou1"></i>
                </span>
            </div>
            <div class="line-item" @click="styleClick('all')">
                <span class="label">规格</span>
                <div class="middle">
                    <div class="big">选择商品</div>
                    <div class="goodsStyle">
                        <div v-for="(item, idx) in styleArrFour" :key="idx" class="style-img">
                            <img :src="item.fileIdPic" alt="" mode="aspectFit" />
                        </div>
                        <div class="count">
                            <span>共{{ styleArr.length }}种单品可选</span>
                        </div>
                    </div>
                </div>
                <span class="r-icon">
                    <i class="iconfont icon-xiangyou1"></i>
                </span>
            </div>
            <div class="line-item" v-if="json.goodsDesc" @click="serverClick('desc')">
                <span class="label">参数</span>
                <div class="middle">
                    <div class="big">查看商品参数</div>
                </div>
                <span class="r-icon">
                    <i class="iconfont icon-xiangyou1"></i>
                </span>
            </div>
        </div>
        <!-- 服务和规则************************************************ -->
        <div class="moreInfo parts" id="infoIdBox">
            <view class="info-head">
                <view class="head-i" @click="switchNav(0)" :class="{ active: fixedIdx == 0 }">
                    <text class="">商品详情</text>
                </view>

                <view class="head-i" @click="switchNav(1)" :class="{ active: fixedIdx == 1 }">
                    <text class="">评价</text>
                    <text class="min">{{ commentTotal }}</text>
                </view>
            </view>

            <view class="infoPices" v-if="fixedIdx == 0">
                <image v-for="(pItem, idx2) in detailDescribePics" :key="idx2" class="" :src="pItem" mode="widthFix" lazy-load="true" @click="previewImage(idx2, detailDescribePics)" />

                <view style="height: 120rpx"></view>
            </view>

            <view class="commentIdBox" id="commentIdBox" v-if="fixedIdx == 1">
                <!-- <view class="info-head">
                <view class="head-i active">
                    <text class="">商品评价{{ commentTotal }}</text>
                </view>

            </view> -->

                <view class="comment-falg mb10">
                    <view class="tag" v-for="(item, idx) in commentTagArr" :key="item.key" @click="goCommPage(item.key)">
                        <text>{{ item.name }} {{ item.value }}</text>
                    </view>
                </view>

                <CommentParts :list="commentArr" />

                <view class="moreComment" @click="goCommPage" v-if="commentTotal > 3">
                    <text class="">查看{{ commentTotal }}全部评价</text>
                    <uni-icons type="right" size="14" color="#999999"></uni-icons>
                </view>
                <view style="height: 120rpx"></view>
            </view>
        </div>


        <view class="commonFoot" v-if="sellClear">
            <view class="foot-btn-box fixed">
                <view class="foot-btn transBg5" @click="goReservation">
                    <text>预 约</text>
                </view>
            </view>
        </view>

        <LoadMask v-if="initMask" />

   

        <GetPhone :isShow.sync="showAuthorize" @finish="finishAuth" />
 
           
      

        <!-- 弹框 -->
        <PopupMsg ref="PopupMsg" :json="json" />

        <BuyPopup ref="BuyPopup" :json="json" :styleArr="styleArr" @chooseFinish="chooseGoodsFinish" />

        <!-- 底部按钮 -->
        <JGoodsNav  @buttonClick="styleClick" ref='JGoodsNav' />
    </view>
</template>

<script>
    import GetPhone from '@/components/GetPhone';
    import CustomHead from '@/components/CustomHead';
    // import Car from '../Car'

    import CommentParts from '@/components/Comment/parts';
  
    import { GoodsInfo, RecommedGoods, PpecificationsList ,GoodsCarEdit} from '@/api/http';
    import Handle from './Handle';
    import PopupMsg from './PopupMsg';

    import BuyPopup from '@/components/BuyPopup';
    import JGoodsNav from '@/components/JGoodsNav';

    const app = getApp();
    export default {
        components: { GetPhone, CustomHead, CommentParts, JGoodsNav , Handle, PopupMsg, BuyPopup },
        data() {
            return {
                //
                headHeight: undefined,
                userId: app.globalData.userId,
                // imgUrls: [
                //     {
                //         url: 'https://oss.qmxip.com/flash_goods/1088155186259398656.png',
                //         isChange: 0
                //     },
                //     {
                //         url: 'https://oss.qmxip.com/flash_goods/1088155186259398656.png',
                //         isChange: 1
                //     },
                //     {
                //         url: 'https://oss.qmxip.com/flash_goods/1088155186259398656.png',
                //         isChange: 2
                //     }
                // ],
                currentImg: 1,
                json: { imgUrls: [] },
                //评价
                commentTagArr: [],
                commentArr: [],
                commentTotal: 0,
                initMask: true,
                detailDescribePics: [],
                //授权
                showAuthorize: false,
                goodsGroupPurchaseId: undefined,
                //售罄
                sellClear: false,
                clearImg: 'https://oss.qmxip.com/flash_goods/1154842763229368320.png',
                //固定顶部
                isFixed: false,
                elementPositionTopArr: [],
                fixedIdx: 0,

                //产品规格
                styleArr: [],
                styleArrFour: [], //截取前四个
                //已选了商品的信息
                selectJson:{},
            };
        },
        computed: {
            selectProduct() {
                return this.$store.getters.selectProduct;
            }
        },
        // watch: {
        //     selectProduct: {
        //         deep: true,
        //         handler (current) {
        //             this.initCars(current)
        //         }
        //     }
        // },
        onLoad(option) {
            // this.goodsGroupPurchaseId = this.$store.getters.goodsGroupPurchaseId;

            // console.log('9啊空间的哈空间很大啊空间和', this.goodsGroupPurchaseId)

            // id=1642802857182818301

            // option.id = '1796421030336917506';

            this.initProduct(option.id);
        },
        methods: {
            initProduct(id) {
                this.initMask = true;

                GoodsInfo(id).then(res => {
                    // console.log('count',res )

                    let json = res.data;

                    json.listPictureSrc = this.$getImg(json.listPicture);

                    json.isJingpin = (json.goodsName || '').includes('精品');

                    json.imgUrls = res.data.picture ? res.data.picture.split(';').map(item => this.$getImg(item, 1)) : [];

                    json.labelArr = (json.productLabelTypeName || '').split(/,|，|;/g);

                    this.detailDescribePics = res.data.detailDescribe ? res.data.detailDescribe.split(';').map(item => this.$getImg(item, 1)) : [];

                    //是否售罄
                    if (json.goodsNum <= 0) {
                        this.sellClear = true;
                    } else {
                        this.sellClear = false;
                    }

                    this.json = json;

                    this.getStyleList();

                    this.getCommentStatic();

                    this.getCommentList();

                    this.initMask = false;

                    this.$nextTick(() => {
                        this.countScrollBox();
                    });

                    app.logRecord('商品详情___' + this.json.goodsName);

                    // setTimeout(()=>{
                    //     this.countScrollBox()
                    // },6000)
                });
            },
            //获取规格
            getStyleList() {
                PpecificationsList({ goodsId: this.json.id, pageNum: '1', pageSize: 100000 }).then(res => {
                    this.styleArr = res.data.map(item => {
                        item.fileIdPic = this.$getImg(item.fileId);

                        return item;
                    });

                    //splice会改变原数组 slice不会
                    this.styleArrFour = res.data.slice(0, 4);
                });
            },

            swiperChange(e) {
                this.currentImg = e.detail.current + 1;
            },
            //分享
            onShareAppMessage(obj) {
                return {
                    title: '甜城小二(' + this.json.goodsName + ')'
                };
            },
            onShareTimeline() {
                return {
                    title: '甜城小二(' + this.json.goodsName + ')'
                };
            },
            //滚动函数
            onPageScroll(e) {
                // console.log('喀喀喀啊空间打卡机爱科技', e)

                // this.scrollTop = e.scrollTop;
                let minTop = this.elementPositionTopArr[0];
                // let secTop = this.elementPositionTopArr[1]

                if (e.scrollTop >= minTop && minTop != 0) {
                    this.isFixed = true;
                } else {
                    this.isFixed = false;
                }

                // if (e.scrollTop >= minTop) {

                //     this.fixedIdx = 0

                //     if (e.scrollTop >= secTop) {
                //         this.fixedIdx = 1
                //     }

                // }
            },
            switchNav(idx) {
                this.fixedIdx = idx;

                uni.pageScrollTo({
                    scrollTop: this.elementPositionTopArr[0],
                    duration: 100
                });
            },
            //获取几个元素的位置
            countScrollBox() {
                //如果使用这个 就会有循环
                // const query = uni.createSelectorQuery().in(this);

                const headHeight = this.headHeight;

                uni.createSelectorQuery()
                    .in(this)
                    .select('#infoIdBox')
                    .boundingClientRect(data => {
                        // 拿到 scroll-view 组件宽度
                        // this.contentScrollW = data.width
                        // console.log('99999999', data)

                        this.elementPositionTopArr[0] = data.top - headHeight;

                        // height = data.height
                    })
                    .exec();
            },
            //评价的分组
            getCommentStatic() {
                this.$axios({ url: 'flash/supermarket/goods/comment/group/statistics', data: { goodsId: this.json.id, supermarketId: this.json.supermarketId, commentCheckStatus: 1 } }).then(res => {
                    // console.log('评价的', res)

                    let arr = [];

                    res.data.map(item => {
                        if (item.value > 0) {
                            let keysArr = item.key.split('#');

                            arr.push({
                                name: keysArr[0],
                                key: keysArr[1],
                                value: item.value
                            });
                        }
                    });

                    this.commentTagArr = arr;
                });
            },
            //拉取几个评价
            getCommentList() {
                this.$axios({
                    url: 'flash/supermarket/goods/comment/page/list',
                    data: {
                        pageNum: 1,
                        commentCheckStatus: 1,
                        pageSize: 3,
                        goodsId: this.json.id,
                        supermarketId: this.json.supermarketId
                    }
                }).then(res => {
                    // console.log('评价的详情', res)

                    this.commentTotal = res.total > 1000 ? '1000+' : res.total;

                    this.commentArr = res.data.map(item => {
                        item.assCommentHeadImg = this.$getImg(item.commentHeadImg, 1);

                        item.picStyle = '';

                        if (item.commentPicture) {
                            item.commentPics = item.commentPicture.split(',').map(p => {
                                return this.$getImg(p, 1);
                            });

                            item.picStyle = item.commentPics.length > 2 ? '' : item.commentPics.length > 1 ? 'middle' : 'big';
                        }
                        return item;
                    });
                });
            },
            //选择了商品
            productChange(e, productId) {
                //剔除商品

                // this.$delete(params,'count',e )
                // console.log('计算',e , this.assProductList.find( i => i.id == productId))

                if (e == 0) {
                    this.$delete(this.selectProduct, productId);
                } else {
                    if (!this.selectProduct[productId]) {
                        this.$set(this.selectProduct, productId, this.json);
                    }
                }

                // app.globalData.selectProduct = this.selectProduct

                this.$store.commit('SET_PRODUCTARR', this.selectProduct);

                // console.log('选择的商品',this.selectProduct)
            },
            //空函数 阻止点击事件
            noneFunc() {},
            chooseGoodsFinish(option) {

                this.selectJson = option
                
                if (!app.globalData.userId) {
                    this.showAuthorize = true;
                } else {
                    console.log('去提交',option);

                    let {type,styleId,num} = option

                    if(type == 'buy'){
                        this.$goNext('/pages/supermarket/order/index?styleId=' + styleId + '&num=' + num );
                    }
                    else if(type == 'car'){
                        this.goJoinCar( option  )
                    }

                }
            },
            //授权回来呢
            finishAuth(){

                this.chooseGoodsFinish( this.selectJson )

            },
            //加入购物车
            goJoinCar(option) {

                GoodsCarEdit({
                    "goodsId":  this.json.id,
                    "goodsNum": option.num,
                    "userId": app.globalData.userId,
                    "specificationsId":option.styleId,
                    "supermarketId": this.json.supermarketId
                }).then(res =>{


                    this.$refs['BuyPopup'].closeBox();

                    // console.log('添加到购物车数量',res)

                    if( res.code == 200){

                        uni.showToast({
                            title: `加入购物车成功`,
                        });

                        this.$refs['JGoodsNav'].iniCar()
                    }

                })
               
            },
            //看更多的评级
            goCommPage(key) {
                this.$goNext(`/pages/supermarket/product/commentpage?goodsId=${this.json.id}&supermarketId=${this.json.supermarketId}&key=${key}`);
            },
            previewImage(ids, arr) {
                uni.previewImage({
                    current: ids,
                    urls: arr
                });
            },
            goReservation() {
                if (app.globalData.userId) {
                    this.$preventRepeatClickOld(() => {
                        this.$axios({
                            url: 'flash/supermarket/order/goods/reservation/saveorupdate',
                            data: {
                                goodsId: this.json.id,
                                userId: app.globalData.userId
                            }
                        }).then(res => {
                            uni.showToast({
                                title: '预约成功',
                                duration: 2000
                            });
                        });
                    }, 2000);
                } else {
                    this.showAuthorize = true;
                }
            },
       
            serverClick(type) {
                this.$refs['PopupMsg'].showFunc(type);
            },
            styleClick(type) {
                this.$refs['BuyPopup'].showFunc(type);
            }
        }
    };
</script>

<style scoped lang="scss">
    .all {
        min-height: 100vh;
        box-sizing: border-box;
    }
    .head-part {
        background: #fff;
    }
    .product-swiper {
        position: relative;
        background: #fff;
        .nums {
            position: absolute;
            right: 10px;
            bottom: 30px;
            background: rgba(0, 0, 0, 0.6);
            color: #fff;
            z-index: 10;
            min-width: 90rpx;
            height: 50rpx;
            line-height: 50rpx;
            padding: 0 10rpx;
            border-radius: 40rpx;
            text-align: center;
        }
        .sellOut {
            position: absolute;
            left: 0;
            bottom: 0;
            width: 100%;
            // background: rgb(255, 45, 70,.1);
            background: rgba(59, 62, 69, 0.6);
            color: #fff;
            padding: 16rpx 0;
            line-height: 1.1;
            font-size: 32rpx;
            text-align: center;
            letter-spacing: 2px;
        }
    }
    .mySwiper {
        height: 45vh;
        margin: 0rpx 0rpx;
        font-size: 0;
        .shuffing-item {
            width: 100%;
            height: 45vh;
            transition: all 0.3s;
            image {
                display: block;
                width: 100%;
                height: 100%;
            }
        }
    }
    .content {
        // padding: 24rpx;
        .name-box {
            position: relative;
            // padding-right: 80rpx;
            // min-height: 140rpx;
            .name {
                // padding: 10rpx 0;
                line-height: 1.4;
                font-size: 42rpx;
                color: #000;
                font-weight: 600;
                margin-bottom: 10rpx;
            }

            // .sellNum {
            //     position: absolute;
            //     right: 0;
            //     top: 10rpx;
            //     font-size: 26rpx;
            //     color: #6666;
            //     margin-bottom: 10rpx;
            // }
        }
        .words-tag {
            padding: 20rpx 0;
            .j-tag {
                border-radius: 10rpx;
                padding: 6rpx 14rpx;
            }
        }
        .desc {
            margin-bottom: 10rpx;
        }
        .tuijianTag {
            height: 90rpx;
            vertical-align: text-bottom;
            margin-right: 6rpx;
        }
        .lijian {
            // height: 34rpx;
            background: rgb(87, 180, 103);
            color: #fff;
            vertical-align: middle;
            margin: 0 8rpx 0 0;
            font-size: 24rpx;
            padding: 6rpx 14rpx;
            border-radius: 6rpx 6rpx 6rpx 6rpx;
            position: relative;
            top: -5rpx;
        }

        .price {
            padding: 0rpx 0 20rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .price-box {
                .big {
                    font-size: 50rpx;
                }
            }
        }
        .maskBox {
            position: relative;
            height: 20rpx;
            width: 100%;
            .sellBox {
                position: absolute;
                width: 100%;
                height: 100%;
                left: 0;
                top: 0;
                background: rgba(255, 255, 255, 0.9);
                z-index: 2;
                image {
                    width: 100%;
                    height: 100%;
                    text-align: center;
                }
            }
            .desc {
                min-height: 50rpx;
            }
        }
    }
    .moreInfo {
        padding: 0rpx 30rpx 20rpx;
        .info-head {
            overflow: hidden;
            line-height: 44px;
            height: 44px;
            font-size: 32rpx;
            margin-bottom: 10rpx;
            .head-i {
                position: relative;
                vertical-align: top;
                display: inline-block;
                padding-right: 40rpx;
                color: #999;
                &.active {
                    color: #222;
                    font-weight: bolder;
                    // &::after{
                    //     position: absolute;
                    //     content: ' ';
                    //     left: 50%;
                    //     bottom: 0;
                    //     width: 30rpx;
                    //     height: 10rpx;
                    //     border-radius: 6rpx;
                    //     background: #ffcc4d;
                    // }
                }
                .min {
                    font-size: 22rpx;
                    margin-left: 4rpx;
                }
            }
        }
    }
    .fixedNav {
        text-align: center;
        .head-i {
            position: relative;
            vertical-align: top;
            display: inline-block;
            margin: 0 30rpx;
            color: #777;
            font-size: 30rpx;
            &.active {
                color: #000;
                &::after {
                    position: absolute;
                    bottom: 0;
                    left: 50%;
                    content: '';
                    height: 10rpx;
                    width: 36rpx;
                    transform: translateX(-50%);
                    border-radius: 6rpx;
                    background: linear-gradient(#ff5305, #ff2d46);
                }
            }
            .min {
                font-size: 22rpx;
                margin-left: 4rpx;
            }
        }
    }
    ::v-deep .fixedNavClass {
        background: #fff !important;
        border-bottom: 1rpx solid #eaeaea;
    }
    .commentIdBox {
        height: 100vh;
    }
    .comment-falg {
        padding: 2rpx 0;
        margin-left: -8px;
        min-height: 44rpx;
        .tag {
            background-color: rgb(255, 248, 225);
            // background:#f5efd2 ;
            color: #333;
            line-height: 1.2;
            border-radius: 3rpx;
            font-size: 24rpx;
            padding: 6rpx 12rpx;
            // margin-left: 8rpx;
            margin: 4rpx 0 4rpx 8rpx;
            display: inline-block;
            vertical-align: top;
        }
    }
    .infoPices {
        font-size: 0;
        padding: 0 0rpx;
        margin: 0 -30rpx;
        image {
            width: 100%;
            margin: 0 0;
        }
    }
    .moreComment {
        padding: 20rpx 0 10rpx;
        color: #999;
        font-size: 24rpx;
        text-align: center;
    }

    // 服务规格
    .line-box {
        padding: 40rpx 40rpx 0;
        color: #999;
        .line-item {
            padding-bottom: 30rpx;
            display: flex;
        }
        .middle {
            flex: 1;
            overflow: hidden;
        }
        .label {
            color: #999;
            width: 80rpx;
        }
        .r-icon {
            color: #999;
            width: 70rpx;
            text-align: right;
        }
        .words {
            display: flex;
            align-items: center;
            color: #333;
            font-size: 26rpx;
            img {
                width: 24rpx;
                height: 24rpx;
                margin: 0 8rpx 0 0;
            }
            .words-i {
                margin-right: 20rpx;
            }
        }
        .big {
            color: #333;
            font-size: 28rpx;
            margin-bottom: 10rpx;
        }
        .goodsStyle {
            display: flex;
            .style-img {
                margin-right: 10rpx;
                border-radius: 4px;
                overflow: hidden;
                width: 32px;
                height: 36px;
                img {
                    width: 100%;
                    height: 100%;
                }
            }
            .count {
                height: 36px;
                background-color: rgb(242, 242, 242);
                font-size: 26rpx;
                text-align: center;
                line-height: 36px;
                padding: 0 10px;
                border-radius: 10px;
            }
        }
    }
</style>
